import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String message;
    public Message(String from, String to, String message) {
        this.from = from;
        this.to = to;
        this.message = message;
    }
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private List<Message> messages=new ArrayList<>();

    @Override
    public void init() throws ServletException {
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        ServletContext context=this.getServletContext();
        TemplateEngine engine= (TemplateEngine) context.getAttribute("engine");
        WebContext webContext=new WebContext(req,resp,context);
        webContext.setVariable("messages",messages);
        String html=engine.process("messageWall",webContext);
        resp.getWriter().write(html);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        String from=req.getParameter("from");
        String to=req.getParameter("to");
        String message=req.getParameter("message");
        messages.add(new Message(from,to,message));
        resp.sendRedirect("message");
    }
}
